import Sker from '@/utils/sker'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.less'
import cm from 'classnames'
import arrow from '/images/arrow.png'
import nullIcon from '/images/null-select.png'
import Button from '../button'
import SearchSvg from '@/svg/search'

function Select(props) {
  const { list, disabled, width = 248, placeholder = '请选择' } = props
  const [expend, setExpend] = useState(false)
  const [selectVal, setSelect] = useState(null)
  const selectEventName = useRef(Symbol('select'))
  const [selectedPerson, setSelectedPerson] = useState('all')
  const [listArr, setListArr] = useState(list)
  const inputRef = useRef(null)

  // 当前选中值
  const placeholders = useMemo(() => {
    if (selectVal) {
      return selectVal.label
    } else {
      return placeholder
    }
  }, [selectVal])

  const select = (e, item) => {
    e.stopPropagation()
    props?.onChange?.(item)
    setSelect(item)
  }

  // 展开收起select
  const selectClick = (ev) => {
    if (disabled) {
      return
    }
    ev.stopPropagation()
    Sker.dispatch('select', { name: selectEventName.current })
    setExpend(!expend)
  }

  const filterData = () => {
    const val = inputRef.current.value
    const newList = list.filter((item) => item.label.includes(val))
    setListArr([...newList])
  }

  const filterDataEnter = (e) => {
    if (e.keyCode === 13) {
      filterData()
    }
  }

  // 全局click点击，Select失焦
  useEffect(() => {
    const click = () => {
      setExpend(false)
    }
    const removeListen = Sker.listen('select', (event) => {
      if (event.detail.name !== selectEventName.current) {
        setExpend(false)
      }
    })
    window.addEventListener('click', click)
    return () => {
      removeListen()
      window.removeEventListener('click', click)
    }
  }, [])

  return (
    <div style={{ width, ...props.style }} className={styles['select-container']}>
      <div className={cm(styles['select-title'], { [styles['disabled']]: disabled })} onClick={selectClick}>
        <div className={cm(styles['select-title-text'], 'textEllipsis')}>{placeholders}</div>
        <img
          src={arrow}
          alt=""
          className={cm(styles['select-title-arrow'], expend ? styles.activeEnter : styles.activeLeave)}
        />
      </div>

      {expend ? (
        <div
          className={cm(styles['select-options-items'], { [styles['select-options-items-flex']]: !listArr.length })}
          onClick={(e) => e.stopPropagation()}
        >
          <div className={styles['options-top']}>
            <div className={styles.left}>
              <p className={selectedPerson === 'all' ? styles.active : ''} onClick={() => setSelectedPerson('all')}>
                全部
              </p>
              <p className={selectedPerson === 'user' ? styles.active : ''} onClick={() => setSelectedPerson('user')}>
                用户
              </p>
            </div>
            <div className={styles.right}>
              <div className={styles.filter}>
                <input
                  maxLength={100}
                  type="text"
                  placeholder="请输入名称"
                  ref={inputRef}
                  onKeyDown={filterDataEnter}
                />
                <SearchSvg className={styles.search} fill="#aaa" onClick={filterData} />
              </div>
              {!listArr.length && (
                <div className={styles.nullBox}>
                  <img src={nullIcon} alt="" />
                  <div>暂无数据</div>
                </div>
              )}
              <ul className={styles.selectBox}>
                {listArr.map((item, index) => (
                  <li
                    key={index}
                    onClick={(e) => select(e, item)}
                    className={cm(styles['select-item'], 'textEllipsis', {
                      [styles.active]: selectVal?.value === item.value,
                    })}
                  >
                    <span className={styles.checked}></span>
                    {item.label || item.value}
                  </li>
                ))}
              </ul>
            </div>
          </div>
          <div className={styles['options-bottom']}>
            <span>已选：{selectVal ? 1 : 0}/1</span>
            <div>
              <Button className={styles.btn} onClick={() => setExpend(false)}>
                取消
              </Button>
              <Button className={cm(styles.btn, styles.btnSure)} type="theme">
                确定
              </Button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  )
}

const Index = React.memo(Select)

export default Index
